package com.liujie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.liujie.pojo.Details;
import com.liujie.pojo.Purse;
import com.liujie.service.DetailsService;
import com.liujie.service.PurseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/purse")
public class PurseController {
    @Autowired
    private PurseService purseService;

    @Autowired
    private DetailsService detailsService;
    /**
     * 查询所有
     * @return 数据
     */
    @GetMapping("/all")
    public List<Purse> getAll(){
        List<Purse> purses = purseService.list();
        return purses;
    }

    /**
     * 消费100元
     * @param purse 钱包数据
     * @return 结果
     */
    @PostMapping("/consume100")
    public boolean consume100(@RequestBody Purse purse){
        int id = purse.getId();
        double balance = purseService.getById(id).getBalance();
        if (balance<100){//余额不足
            return false;
        }
        LambdaUpdateWrapper<Purse> luw=new LambdaUpdateWrapper<>();
        luw.set(Purse::getBalance,balance-100);
        luw.eq(Purse::getId,id);
        boolean update = purseService.update(luw);
        Details details=new Details();
        details.setPurseId(id);
        details.setTime(new Date());
        details.setType("消费");
        details.setAmount(100);
        boolean save = detailsService.save(details);
        if (update && save){
            return true;
        }
        return false;
    }

    /**
     * 退款20元
     * @param purse 钱包数据
     * @return 结果
     */
    @PostMapping("/refund20")
    public boolean refund20(@RequestBody Purse purse){
        int id = purse.getId();
        LambdaUpdateWrapper<Purse> luw=new LambdaUpdateWrapper<>();
        luw.set(Purse::getBalance,purseService.getById(id).getBalance()+20);
        luw.eq(Purse::getId,id);
        boolean update = purseService.update(luw);
        Details details=new Details();
        details.setPurseId(id);
        details.setTime(new Date());
        details.setType("退款");
        details.setAmount(20);
        boolean save = detailsService.save(details);
        if (update && save){
            return true;
        }
        return false;
    }

    /**
     * 钱包变动明细
     * @param id 钱包id
     * @return 数据
     */
    @GetMapping("/details/{id}")
    public List<Details> details(@PathVariable int id){
        LambdaQueryWrapper<Details> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Details::getPurseId,id);
        List<Details> details = detailsService.list(lqw);
        return details;
    }
}
